package com.hh.game.client;

import org.java_websocket.client.DefaultSSLWebSocketClientFactory;
import org.java_websocket.handshake.ServerHandshake;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;

public class SocketAutoSendClient extends SocketClient {

    public SocketAutoSendClient(String uri, CountDownLatch latch, SockectOnConnctionMsg msg) throws Exception {
        super(uri, latch, msg);
    }


    @Override
    public void send() {
        super.send();
    }

    @Override
    public void onOpen(ServerHandshake arg0) {
        send();
    }

    private void trustAllHosts(SocketAutoSendClient appClient) {
        appClient.setWebSocketFactory(getSslWebSock());
    }

    private DefaultSSLWebSocketClientFactory getSslWebSock() {
        DefaultSSLWebSocketClientFactory sslWebSock = null;
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {

            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {
            }
        }};
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            sslWebSock = new DefaultSSLWebSocketClientFactory(sc);
        } catch (Exception e) {
        }
        return sslWebSock;
    }

    @Override
    public void onMessage(ByteBuffer bytes) {
        super.onMessage(bytes);
        this.close();
    }

    @Override
    public void onClose(int arg0, String arg1, boolean arg2) {
        super.onClose(arg0, arg1, arg2);
    }

    @Override
    public void onError(Exception arg0) {
        super.onError(arg0);
    }

    @Override
    public void onMessage(String arg0) {
        System.out.println(arg0);
    }
}
